import React, { useEffect, useState } from 'react'
import { useModel } from '@umijs/max'
import { Form, InputNumber, Checkbox } from 'antd'
import styles from './index.less'

const gainSetType = {
  1: '固定价格',
  2: '自定义价格',
  3: '按租金比例'
}
export default ({ value, onChange, data, form, disabled }) => {
  const [gainList, setGainList] = useState([])

  useEffect(() => {
    if (value) {
      setGainList(
        data.map((i) => {
          const item = value.find((v) => v.id === i.id)
          const amount = item ? item.amount : i.price
          const formName = `other_price-${i.id}`

          form.setFieldValue(formName, amount)

          return {
            ...i,
            checked: item ? true : false,
            amount
          }
        })
      )
    } else {
      setGainList(
        data
          ? data.map((i) => ({
            ...i,
            amount: i.price
          }))
          : []
      )
    }
  }, [])

  const handleChange = (list) => {
    setGainList(list)
    onChange(list.filter((i) => i.checked))
  }

  const handleCheckGain = (e, index) => {
    const newList = [...gainList]

    if (e) {
      const item = newList[index]
      if (item.type === 1) {
        const formName = `other_price-${item.id}`
        form.setFieldValue(formName, item.amount || item.price)
      }
    }
    newList[index].checked = e
    handleChange(newList)
  }

  const handleInputPrice = (e, index, type) => {
    if (type === 1) return
    const newList = [...gainList]
    newList[index].amount = e
    handleChange(newList)
  }

  return (
    <>
      {gainList.map((gain, index) => (
        <div key={gain.id}>
          <Form.Item label=''>
            <Checkbox
              checked={gain.checked}
              disabled={disabled}
              onChange={(e) => handleCheckGain(e.target.checked, index)}
            >
              {gain.name}（{gainSetType[gain.type]}）
            </Checkbox>
          </Form.Item>
          <Form.Item
            label=''
            name={`other_price-${gain.id}`}
            rules={[{ required: gain.checked && gain.type === 2 }]}
          >
            <InputNumber
              prefix={gain.type === 3 ? '' : '价格'}
              precision={2}
              defaultValue={Number(gain.amount)}
              addonAfter={gain.type === 3 ? '%' : '元'}
              className={gain.type === 3 ? styles.input_number_item_percent : styles.input_number_item}
              onChange={(e) => handleInputPrice(e, index, gain.type)}
              bordered={false}
              disabled={disabled || gain.type !== 2}
            />
          </Form.Item>
        </div>
      ))}
    </>
  )
};
